using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Newtonsoft.Json;
using UnityEngine;
using UnityEngine.Scripting;
using Voodoo.Sauce.Common.Utils;
using Voodoo.Sauce.Core;
using Voodoo.Sauce.Internal;
using Voodoo.Sauce.Internal.Analytics;
using Voodoo.Sauce.Internal.Utils;
using Voodoo.Sauce.Privacy.UI;

namespace Voodoo.Sauce.Privacy
{
	[Preserve]
	internal class PrivacyManager : PrivacyCore
	{
		public struct AdvertisingStatus
		{
			public string Idfa;

			public bool AdTrackingEnabled;
		}

		private static class IdfaHelper
		{
			public static async Task<AdvertisingStatus> RequestAdvertisingId(VoodooSettings voodooSettings, PrivacyCore privacy)
			{
				string idfa = "00000000-0000-0000-0000-000000000000";
				bool adTrackingEnabled = false;
				AdvertisingStatus result = default(AdvertisingStatus);
				result.Idfa = idfa;
				result.AdTrackingEnabled = adTrackingEnabled;
				return result;
			}
		}

		private static class VendorIdHelperAndroid
		{
			private delegate void RequestVendorIdCallback(string vendorId);

			private const string TAG = "VendorIdHelperAndroid";

			private static string _vendorId;

			private static readonly bool IS_ANDROID;

			internal static async Task<string> RequestVendorId()
			{
				if (!IS_ANDROID)
				{
					return "";
				}
				_vendorId = await GetAndroidVendorIdAsync();
				return _vendorId;
			}

			private static Task<string> GetAndroidVendorIdAsync()
			{
				TaskCompletionSource<string> tcs = new TaskCompletionSource<string>();
				GetAppSetIdAndroidPlayService(delegate(string vendorId)
				{
					tcs.TrySetResult(vendorId);
				});
				return tcs.Task;
			}

			private static void DisposeObjects(List<AndroidJavaObject> androidJavaObjects)
			{
				foreach (AndroidJavaObject androidJavaObject in androidJavaObjects)
				{
					androidJavaObject?.Dispose();
				}
			}

			private static void GetAppSetIdAndroidPlayService(RequestVendorIdCallback callBack)
			{
				List<AndroidJavaObject> list = new List<AndroidJavaObject>();
				try
				{
					AndroidJavaClass androidJavaClass = new AndroidJavaClass("com.google.android.gms.tasks.Tasks");
					AndroidJavaClass androidJavaClass2 = new AndroidJavaClass("com.google.android.gms.appset.AppSet");
					AndroidJavaObject @static = new AndroidJavaClass("com.unity3d.player.UnityPlayer").GetStatic<AndroidJavaObject>("currentActivity");
					list.Add(androidJavaClass);
					list.Add(androidJavaClass2);
					list.Add(@static);
					AndroidJavaObject androidJavaObject = @static?.Call<AndroidJavaObject>("getApplicationContext", Array.Empty<object>());
					if (androidJavaObject == null)
					{
						throw new Exception("applicationContext is null");
					}
					list.Add(androidJavaObject);
					AndroidJavaObject androidJavaObject2 = androidJavaClass2.CallStatic<AndroidJavaObject>("getClient", new object[1] { androidJavaObject });
					if (androidJavaObject2 == null)
					{
						throw new Exception("appSetClientObject is null");
					}
					list.Add(androidJavaObject2);
					AndroidJavaObject androidJavaObject3 = androidJavaObject2.Call<AndroidJavaObject>("getAppSetIdInfo", Array.Empty<object>());
					if (androidJavaObject3 == null)
					{
						throw new Exception("taskObject is null");
					}
					list.Add(androidJavaObject3);
					AndroidJavaObject androidJavaObject4 = androidJavaClass.CallStatic<AndroidJavaObject>("await", new object[1] { androidJavaObject3 });
					if (androidJavaObject4 != null)
					{
						list.Add(androidJavaObject4);
						string vendorId = androidJavaObject4.Call<string>("getId", Array.Empty<object>());
						if (androidJavaObject4.Call<int>("getScope", Array.Empty<object>()) != 2)
						{
							vendorId = "";
						}
						DisposeObjects(list);
						callBack(vendorId);
					}
					else
					{
						callBack("");
						DisposeObjects(list);
					}
				}
				catch (AndroidJavaException ex)
				{
					VoodooLog.LogError(Module.PRIVACY, "VendorIdHelperAndroid", "[VendorIdHelperAndroid.GetIdfaAndroidPlayService] Class not found with error " + ex.Message + "\n" + ex.StackTrace);
					VoodooSauceCore.GetCrashReport().LogException(ex);
					callBack("");
				}
				catch (Exception ex2)
				{
					VoodooLog.LogError(Module.PRIVACY, "VendorIdHelperAndroid", "[VendorIdHelperAndroid.GetIdfaAndroidPlayService] there was an error trying to get advertising id and tracking " + ex2.Message + "\n" + ex2.StackTrace);
					VoodooSauceCore.GetCrashReport().LogException(ex2);
					callBack("");
				}
				finally
				{
					DisposeObjects(list);
				}
			}
		}

		private const string TAG = "PrivacyManager";

		private const int CONSENT_VALIDITY_PERIOD_IN_DAY = 182;

		private VoodooSettings _voodooSettings;

		private Action<GdprConsent> _onConsentGiven;

		private Action<GdprConsent> _onConsentUpdate;

		private Action<bool> _onPrivacyShown;

		private Action _onInternetAvailable;

		private Action _onGameStarted;

		private Action _onGameFinished;

		private Action _tryOpenDebugger;

		private Action _onDeleteDataRequest;

		private Func<bool> _hasGameStarted;

		private IPrivacyCanvas _privacyCanvas;

		private IRequest _request;

		private string _gdprTexts;

		private bool _isInitialized;

		private bool _showOfferWall;

		private PrivacyConfiguration _privacyConfiguration;

		private bool _alreadyAppliedGdpr;

		private int _startPlayDate;

		private int _limitedPlayTimeInSecond;

		private IPrivacyUIManager _uiManager;

		private NeedConsent _serverConsent;

		private NeedConsent.OfferWallStatus _offerWallStatus;

		private Action _onSettingsClosed;

		private IPrivacyAPI _privacyAPI;

		private IConsentManagementProvider _consentManagementProvider;

		private const string PLAYER_PREF_IS_SIXTEEN_OR_OLDER = "Voodoo.Sauce.Privacy.IsOverSixteen";

		private const string PLAYER_PREF_ADS_CONSENT = "Voodoo.Sauce.Privacy.AdsConsent";

		private const string PLAYER_PREF_ANALYTICS_CONSENT = "Voodoo.Sauce.Privacy.AnalyticsConsent";

		private const string PLAYER_PREF_PRIVACY_VERSION = "Voodoo.Sauce.Privacy.PrivacyVersion";

		private const string PLAYER_PREF_NEED_SEND_CONSENT = "Voodoo.Sauce.Privacy.NeedSendConsent";

		private const string PLAYER_PREF_LAST_CONSENT_DATE = "Voodoo.Sauce.Privacy.LastConsentDate";

		private const string PLAYER_PREF_LAST_PLAY_DATE = "Voodoo.Sauce.Privacy.LastPlayDate";

		private const string PLAYER_PREF_LAST_PLAY_TIME = "Voodoo.Sauce.Privacy.LastPlayTime";

		private const string PLAYER_PREF_AD_TRACKING_ENABLED = "Voodoo.Sauce.Privacy.AdTrackingEnabled";

		private const string PLAYER_PREF_PRIVACY_LIST = "Voodoo.Sauce.Privacy.List";

		private const string PLAYER_PREF_USER_REQUEST_TO_BE_FORGOTTEN = "Voodoo.Sauce.Privacy.UserRequestedToBeForgotten";

		private const string PLAYER_PREF_SOURCEPOINT_SHOWN = "Voodoo.Sauce.Privacy.SourcepointShown";

		private IPrivacyUIManager UIManager => _uiManager ?? (_uiManager = new PrivacyUIManager());

		private IPrivacyAPI PrivacyAPI
		{
			get
			{
				if (_privacyAPI == null)
				{
					_privacyAPI = new PrivacyAPI();
					_privacyAPI.Initialize(_request);
				}
				return _privacyAPI;
			}
		}

		public override async Task Instantiate(VoodooSettings voodooSettings)
		{
			_voodooSettings = voodooSettings;
			await SynchronizeAdvertisingId();
		}

		public override void Initialize(PrivacyManagerParameters parameters)
		{
			_voodooSettings = parameters.voodooSettings;
			_onConsentGiven = parameters.onConsentGiven;
			_onConsentUpdate = parameters.onConsentUpdate;
			_onPrivacyShown = parameters.onPrivacyShown;
			parameters.onInternetAvailable = (Action)Delegate.Combine(parameters.onInternetAvailable, (Action)delegate
			{
				_onInternetAvailable?.Invoke();
			});
			parameters.onGameStarted = (Action)Delegate.Combine(parameters.onGameStarted, (Action)delegate
			{
				_onGameStarted?.Invoke();
			});
			parameters.onGameFinished = (Action)Delegate.Combine(parameters.onGameFinished, (Action)delegate
			{
				_onGameFinished?.Invoke();
			});
			_hasGameStarted = parameters.hasGameStarted;
			_tryOpenDebugger = parameters.tryOpenDebugger;
			_onDeleteDataRequest = parameters.onDeleteDataRequest;
			_privacyCanvas = parameters.canvas;
			_request = parameters.request;
			_privacyAPI = parameters.privacyAPI;
			_uiManager = parameters.privacyUIManager;
			_privacyConfiguration = parameters.privacyConfiguration;
			LoadCache();
			UIManager.Initialize(new IPrivacyUIManagerParameters
			{
				privacyCanvas = _privacyCanvas,
				voodooSettings = _voodooSettings,
				gdprTexts = null
			});
			TrySynchronizeWithServer();
		}

		internal override void ShowPrivacyAuthorization()
		{
			if (IsCmpActive())
			{
				OpenCmpPrivacySettings();
			}
			else
			{
				UpdateConsent();
			}
		}

		public override string GetAdvertisingId(bool forceZerosForLimitedAdTracking = true)
		{
			if (forceZerosForLimitedAdTracking && !_adTrackingEnabled)
			{
				return "00000000-0000-0000-0000-000000000000";
			}
			return _idfa;
		}

		internal override void OpenPrivacySettings(Action onSettingsClosed = null)
		{
			bool idfaAuthorizationStatusDeniedOrRestricted = GetAuthorizationStatus() == IdfaAuthorizationStatus.Denied || GetAuthorizationStatus() == IdfaAuthorizationStatus.Restricted;
			_onSettingsClosed = onSettingsClosed;
			if (!_isInitialized)
			{
				UIManager.OpenPrivacyNotInitializedPopupScreen(delegate
				{
					UIManager.ClosePopupScreen();
				}, _voodooSettings, _privacyCanvas);
			}
			else if (IsCmpActive())
			{
				UIManager.OpenCmpSettingsScreen(idfaAuthorizationStatusDeniedOrRestricted, _idfa, OpenCmpPrivacySettings, DeleteData, RequestAccessToData, _tryOpenDebugger.Invoke, CloseCmpPrivacySettings);
			}
			else
			{
				UIManager.OpenSettingsScreen(_adsConsent, _analyticsConsent, idfaAuthorizationStatusDeniedOrRestricted, _idfa, UpdatePrivacyConsent, DeleteData, RequestAccessToData, _tryOpenDebugger.Invoke, ClosePrivacySettings);
			}
		}

		private void CloseCmpPrivacySettings()
		{
			UIManager.CloseCmpSettingsScreen();
			_onSettingsClosed?.Invoke();
		}

		private void ClosePrivacySettings()
		{
			UIManager.CloseSettingsScreen();
			_onSettingsClosed?.Invoke();
		}

		private async void OpenCmpPrivacySettings()
		{
			CmpConsent cmpConsent = await _consentManagementProvider.OpenPrivacySettings();
			VoodooLog.LogDebug(Module.PRIVACY, "PrivacyManager", "PrivacyManager.OpenCMPPrivacySettings: privacyConsent:" + JsonConvert.SerializeObject(cmpConsent));
			UpdatePrivacyConsent(new PrivacyUpdate
			{
				adsConsent = cmpConsent.privacyConsent.adsConsent,
				analyticsConsent = cmpConsent.privacyConsent.analyticsConsent
			});
		}

		private async void UpdatePrivacyConsent(PrivacyUpdate privacyUpdate)
		{
			if (_isGdprApplicable && (_adsConsent != privacyUpdate.adsConsent || _analyticsConsent != privacyUpdate.analyticsConsent))
			{
				UIManager.OpenLoadingScreen();
				if (await SendConsent(privacyUpdate.adsConsent, privacyUpdate.analyticsConsent))
				{
					UpdateCachedConsent(privacyUpdate);
					UIManager.CloseLoadingScreen();
					UIManager.OpenUpdatePrivacySuccessPopupScreen(delegate
					{
						UIManager.ClosePopupScreen();
						UIManager.CloseSettingsScreen();
						_onSettingsClosed?.Invoke();
					});
				}
				else
				{
					UIManager.CloseLoadingScreen();
					UIManager.OpenUpdatePrivacyErrorPopupScreen(delegate
					{
						UIManager.ClosePopupScreen();
						UIManager.CloseSettingsScreen();
						_onSettingsClosed?.Invoke();
					});
				}
			}
			else if (_adsConsent != privacyUpdate.adsConsent || _analyticsConsent != privacyUpdate.analyticsConsent)
			{
				UpdateCachedConsent(privacyUpdate);
				UIManager.OpenUpdatePrivacySuccessPopupScreen(delegate
				{
					UIManager.ClosePopupScreen();
					UIManager.CloseSettingsScreen();
					_onSettingsClosed?.Invoke();
				});
			}
			else
			{
				UIManager.CloseSettingsScreen();
				_onSettingsClosed?.Invoke();
			}
		}

		private void UpdateCachedConsent(PrivacyUpdate privacyUpdate)
		{
			_adsConsent = privacyUpdate.adsConsent;
			CacheAdsConsent(_adsConsent);
			_analyticsConsent = privacyUpdate.analyticsConsent;
			CacheAnalyticsConsent(_analyticsConsent);
			_gdprConsent = new GdprConsent
			{
				ExplicitConsentGivenForAds = privacyUpdate.adsConsent,
				ExplicitConsentGivenForAnalytics = privacyUpdate.analyticsConsent,
				IsEmbargoedCountry = _serverConsent.embargoed_country,
				IsGdprApplicable = _serverConsent.is_gdpr,
				IsAdsEnforcement = _serverConsent.ads_enforcement,
				IsAdjustEnforcement = _serverConsent.adjust_enforcement,
				IsVANEnforcement = _serverConsent.van_enforcement,
				CountryCode = _serverConsent.country_code
			};
			_onConsentUpdate(_gdprConsent);
		}

		private async void DeleteData(string email)
		{
			if (!PrivacyUtils.IsValidEmail(email))
			{
				UIManager.OpenEmailErrorPopupScreen(UIManager.ClosePopupScreen);
				return;
			}
			UIManager.OpenLoadingScreen();
			DeleteDataParameters p = new DeleteDataParameters
			{
				uuid = _idfa,
				appVersion = PrivacyUtils.GetAppVersion(),
				vsVersion = PrivacyUtils.GetVSVersion(),
				bundleId = Application.identifier,
				platform = PrivacyUtils.GetOsType(),
				locale = PrivacyUtils.GetLocale(),
				email = email,
				studioName = "Voodoo",
				gdprType = (int)PrivacyUtils.GetGDPRType(),
				vendor_id = null,
				voodoo_user_id = AnalyticsUserIdHelper.GetUserId()
			};
			PrivacyRequest privacyRequest = await PrivacyAPI.DeleteDataRequest(p);
			UIManager.CloseLoadingScreen();
			if (privacyRequest == null)
			{
				UIManager.OpenConnexionErrorPopupScreen(delegate
				{
					UIManager.ClosePopupScreen();
				});
			}
			else if (privacyRequest.success == "true")
			{
				CacheUserRequestedToBeForgotten(value: true);
				_onDeleteDataRequest?.Invoke();
				UIManager.OpenSuccessPopupScreen(delegate
				{
					UIManager.ClosePopupScreen();
					UIManager.CloseDeleteScreen();
					_onSettingsClosed?.Invoke();
				});
			}
			else
			{
				UIManager.OpenErrorPopupScreen(privacyRequest.errorMessage, delegate
				{
					UIManager.ClosePopupScreen();
				});
			}
		}

		private async void RequestAccessToData(UserDetails userDetails)
		{
			if (!PrivacyUtils.IsValidEmail(userDetails.email))
			{
				UIManager.OpenEmailErrorPopupScreen(UIManager.ClosePopupScreen);
				return;
			}
			UIManager.OpenLoadingScreen();
			AccessDataParameters p = new AccessDataParameters
			{
				uuid = _idfa,
				appVersion = PrivacyUtils.GetAppVersion(),
				vsVersion = PrivacyUtils.GetVSVersion(),
				bundleId = Application.identifier,
				platform = PrivacyUtils.GetOsType(),
				locale = PrivacyUtils.GetLocale(),
				email = userDetails.email,
				studioName = "Voodoo",
				gdprType = (int)PrivacyUtils.GetGDPRType(),
				vendor_id = _vendorId,
				voodoo_user_id = AnalyticsUserIdHelper.GetUserId()
			};
			PrivacyRequest privacyRequest = await PrivacyAPI.AccessDataRequest(p);
			UIManager.CloseLoadingScreen();
			if (privacyRequest == null)
			{
				UIManager.OpenConnexionErrorPopupScreen(delegate
				{
					UIManager.ClosePopupScreen();
				});
			}
			else if (privacyRequest.success == "true")
			{
				UIManager.OpenSuccessPopupScreen(delegate
				{
					UIManager.ClosePopupScreen();
					UIManager.CloseAccessDataScreen();
					_onSettingsClosed?.Invoke();
				});
			}
			else
			{
				UIManager.OpenErrorPopupScreen(privacyRequest.errorMessage, delegate
				{
					UIManager.ClosePopupScreen();
				});
			}
		}

		private async Task SynchronizeAdvertisingId()
		{
			AdvertisingStatus advertisingStatus = await IdfaHelper.RequestAdvertisingId(_voodooSettings, this);
			_idfa = advertisingStatus.Idfa;
			_adTrackingEnabled = advertisingStatus.AdTrackingEnabled;
			_idfaAuthorizationStatus = (HasLimitAdTrackingEnabled() ? IdfaAuthorizationStatus.Denied : IdfaAuthorizationStatus.Authorized);
		}

		private void TrySynchronizeWithServer()
		{
			if (IsInternetAvailable())
			{
				SynchronizeWithServer();
				return;
			}
			OnSynchronizeWithServerEnd(isSuccess: false);
			_onInternetAvailable = (Action)Delegate.Combine(_onInternetAvailable, new Action(SynchronizeWithServer));
		}

		private async void SynchronizeWithServer()
		{
			_onInternetAvailable = (Action)Delegate.Remove(_onInternetAvailable, new Action(SynchronizeWithServer));
			_serverConsent = await RequestConsent();
			if (_serverConsent != null)
			{
				_isGdprApplicable = _serverConsent.is_gdpr;
				_isCcpaApplicable = _serverConsent.is_ccpa;
				_offerWallStatus = _serverConsent.OfferWall;
				UIManager.Initialize(new IPrivacyUIManagerParameters
				{
					privacyCanvas = _privacyCanvas,
					voodooSettings = _voodooSettings,
					gdprTexts = _serverConsent.texts
				});
				Type cmpType = GetCmpType();
				if (_isGdprApplicable && !PlatformUtils.UNITY_EDITOR && cmpType != null)
				{
					_consentManagementProvider = (IConsentManagementProvider)Activator.CreateInstance(cmpType);
					TryUpdateConsent();
				}
				else if (IsCachePresent())
				{
					if (NeedUpdateLocalConsent())
					{
						TryUpdateConsent();
						return;
					}
					OnSynchronizeWithServerEnd(isSuccess: true);
					if (NeedSendConsent())
					{
						TrySendConsent();
					}
				}
				else if (_isGdprApplicable)
				{
					TryUpdateConsent();
				}
				else
				{
					CacheUserRequestedToBeForgotten(value: false);
					CacheSixteenOrOlder(isSixteenOrOlder: true);
					_adsConsent = true;
					CacheAdsConsent(_adsConsent);
					_analyticsConsent = true;
					CacheAnalyticsConsent(_analyticsConsent);
					OnSynchronizeWithServerEnd(isSuccess: true);
				}
			}
			else
			{
				OnSynchronizeWithServerEnd(isSuccess: false);
				if (!IsInternetAvailable())
				{
					_onInternetAvailable = (Action)Delegate.Combine(_onInternetAvailable, new Action(SynchronizeWithServer));
				}
			}
		}

		private async void OnSynchronizeWithServerEnd(bool isSuccess)
		{
			_isInitialized = isSuccess;
			_gdprConsent = new GdprConsent
			{
				ExplicitConsentGivenForAds = _adsConsent,
				ExplicitConsentGivenForAnalytics = _analyticsConsent,
				IsEmbargoedCountry = (isSuccess && _serverConsent.embargoed_country),
				IsGdprApplicable = (isSuccess ? _serverConsent.is_gdpr : _alreadyAppliedGdpr),
				IsAdsEnforcement = (isSuccess && _serverConsent.ads_enforcement),
				IsAdjustEnforcement = (isSuccess && _serverConsent.adjust_enforcement),
				IsVANEnforcement = (isSuccess && _serverConsent.van_enforcement),
				CountryCode = (isSuccess ? _serverConsent.country_code : null)
			};
			_onConsentGiven(_gdprConsent);
		}

		private void TryUpdateConsent()
		{
			if (!_hasGameStarted())
			{
				UpdateConsent();
			}
			else
			{
				_onGameFinished = (Action)Delegate.Combine(_onGameFinished, new Action(UpdateConsent));
			}
		}

		private async void UpdateConsent()
		{
			bool mustSendConsent = true;
			PrivacyConsent privacyConsent;
			if (IsCmpActive())
			{
				CmpConsent cmpConsent = await _consentManagementProvider.GetConsent(_onPrivacyShown);
				mustSendConsent = cmpConsent.consentUpdated;
				privacyConsent = cmpConsent.privacyConsent;
			}
			else
			{
				privacyConsent = await AskConsent();
			}
			_isInitialized = true;
			CacheUserRequestedToBeForgotten(value: false);
			CacheConsent(privacyConsent);
			if (_serverConsent.is_gdpr)
			{
				_alreadyAppliedGdpr = _serverConsent.is_gdpr;
				if (mustSendConsent)
				{
					CacheNeedSendConsent(needSend: true);
					CachePrivacyVersion(_serverConsent.privacy_version);
					CachePrivacyList();
					CacheConsentDate();
					CacheAdTrackingEnabled(_adTrackingEnabled);
					TrySendConsent();
				}
			}
			_onGameFinished = (Action)Delegate.Remove(_onGameFinished, new Action(UpdateConsent));
			_gdprConsent = new GdprConsent
			{
				ExplicitConsentGivenForAds = privacyConsent.adsConsent,
				ExplicitConsentGivenForAnalytics = privacyConsent.analyticsConsent,
				IsEmbargoedCountry = _serverConsent.embargoed_country,
				IsGdprApplicable = _serverConsent.is_gdpr,
				IsAdsEnforcement = _serverConsent.ads_enforcement,
				IsAdjustEnforcement = _serverConsent.adjust_enforcement,
				IsVANEnforcement = _serverConsent.van_enforcement,
				CountryCode = _serverConsent.country_code
			};
			_onConsentGiven(_gdprConsent);
		}

		private void TrySendConsent()
		{
			if (IsInternetAvailable())
			{
				SendConsent();
			}
			else
			{
				_onInternetAvailable = (Action)Delegate.Combine(_onInternetAvailable, new Action(SendConsent));
			}
		}

		private async Task<PrivacyConsent> AskConsent()
		{
			_onPrivacyShown(obj: true);
			PrivacyConsent result = await UIManager.GetPrivacyConsent();
			_onPrivacyShown(obj: false);
			return result;
		}

		private Task<NeedConsent> RequestConsent()
		{
			NeedConsentParams data = new NeedConsentParams
			{
				bundle_id = Application.identifier,
				popup_version = PrivacyUtils.GetPopupVersion(),
				user = PrivacyUtils.GetUserStatus(),
				os_type = PrivacyUtils.GetOsType(),
				app_version = PrivacyUtils.GetAppVersion(),
				vs_version = PrivacyUtils.GetVSVersion(),
				locale = PrivacyUtils.GetLocale(),
				uuid = _idfa,
				studio_name = "Voodoo",
				gdpr_type = (int)PrivacyUtils.GetGDPRType(),
				vendor_id = null,
				voodoo_user_id = AnalyticsUserIdHelper.GetUserId(),
				idfa_authorization_status = _idfaAuthorizationStatus.ToString()
			};
			return PrivacyAPI.NeedConsent(data);
		}

		private async void SendConsent()
		{
			_onInternetAvailable = (Action)Delegate.Remove(_onInternetAvailable, new Action(SendConsent));
			ConsentInsightsParams data = new ConsentInsightsParams
			{
				bundle_id = Application.identifier,
				popup_version = PrivacyUtils.GetPopupVersion(),
				user = PrivacyUtils.GetUserStatus(),
				ads_consent = _adsConsent,
				analytics_consent = _analyticsConsent,
				os_type = PrivacyUtils.GetOsType(),
				app_version = PrivacyUtils.GetAppVersion(),
				vs_version = PrivacyUtils.GetVSVersion(),
				locale = PrivacyUtils.GetLocale(),
				uuid = _idfa,
				studio_name = "Voodoo",
				gdpr_type = (int)PrivacyUtils.GetGDPRType(),
				vendor_id = _vendorId,
				voodoo_user_id = AnalyticsUserIdHelper.GetUserId(),
				idfa_authorization_status = _idfaAuthorizationStatus.ToString()
			};
			if (await PrivacyAPI.ConsentInsights(data))
			{
				CacheNeedSendConsent(needSend: false);
			}
			else
			{
				_onInternetAvailable = (Action)Delegate.Combine(_onInternetAvailable, new Action(SendConsent));
			}
		}

		private async Task<bool> SendConsent(bool adsConsent, bool analyticsConsent)
		{
			_onInternetAvailable = (Action)Delegate.Remove(_onInternetAvailable, new Action(SendConsent));
			ConsentInsightsParams data = new ConsentInsightsParams
			{
				bundle_id = Application.identifier,
				popup_version = PrivacyUtils.GetPopupVersion(),
				user = PrivacyUtils.GetUserStatus(),
				ads_consent = adsConsent,
				analytics_consent = analyticsConsent,
				os_type = PrivacyUtils.GetOsType(),
				app_version = PrivacyUtils.GetAppVersion(),
				vs_version = PrivacyUtils.GetVSVersion(),
				locale = PrivacyUtils.GetLocale(),
				uuid = _idfa,
				studio_name = "Voodoo",
				gdpr_type = (int)PrivacyUtils.GetGDPRType(),
				vendor_id = _vendorId,
				voodoo_user_id = AnalyticsUserIdHelper.GetUserId(),
				idfa_authorization_status = _idfaAuthorizationStatus.ToString()
			};
			return await PrivacyAPI.ConsentInsights(data);
		}

		private Type GetCmpType()
		{
			List<Type> types = AssembliesUtils.GetTypes(typeof(IConsentManagementProvider));
			types = types.Select((Type cmpClass) => cmpClass).ToList();
			if (types.Any())
			{
				return types[0];
			}
			return null;
		}

		private void CacheConsent(PrivacyConsent privacyConsent)
		{
			CacheSixteenOrOlder(privacyConsent.isSixteenOrOlder);
			_adsConsent = privacyConsent.adsConsent;
			CacheAdsConsent(_adsConsent);
			_analyticsConsent = privacyConsent.analyticsConsent;
			CacheAnalyticsConsent(_analyticsConsent);
		}

		private void LoadCache()
		{
			if (IsCachePresent())
			{
				_adsConsent = GetAdsConsent();
				_analyticsConsent = GetAnalyticsConsent();
				_alreadyAppliedGdpr = GetAlreadyAppliedGdpr();
			}
		}

		private bool NeedUpdateLocalConsent()
		{
			if (_serverConsent.is_gdpr)
			{
				if (!NeedConsentToNewVoodooPolicy() && !NeedConsentToNew3rdPartyPolicy() && !ConsentNotUpToDate())
				{
					return AdTrackingIsReEnabled();
				}
				return true;
			}
			return false;
		}

		private bool NeedConsentToNewVoodooPolicy()
		{
			return _serverConsent.privacy_version != GetPrivacyVersion();
		}

		private bool NeedConsentToNew3rdPartyPolicy()
		{
			return PrivacyUtils.GetPrivacyPolicyUrls().ToArray().Except(GetPrivacyList())
				.Any();
		}

		private static bool ConsentNotUpToDate()
		{
			int consentDate = GetConsentDate();
			int num = TimeUtils.NowAsTimeStamp();
			if (consentDate > 0)
			{
				return TimeUtils.GetDaysFromSeconds(num - consentDate) >= 182;
			}
			return false;
		}

		private bool AdTrackingIsReEnabled()
		{
			if (!GetCachedAdTrackingEnabled())
			{
				return _adTrackingEnabled;
			}
			return false;
		}

		private bool IsInternetAvailable()
		{
			return Application.internetReachability != NetworkReachability.NotReachable;
		}

		private bool IsCmpActive()
		{
			if (_isGdprApplicable)
			{
				return _consentManagementProvider != null;
			}
			return false;
		}

		internal override string GetCmpName()
		{
			if (_consentManagementProvider == null)
			{
				return "None";
			}
			return _consentManagementProvider.GetName();
		}

		private void CacheAdsConsent(bool consent)
		{
			NintendoPlayerPrefs.SetInt("Voodoo.Sauce.Privacy.AdsConsent", consent ? 1 : 0);
		}

		private bool GetAdsConsent()
		{
			return NintendoPlayerPrefs.GetInt("Voodoo.Sauce.Privacy.AdsConsent", -1) == 1;
		}

		private void CacheAnalyticsConsent(bool consent)
		{
			NintendoPlayerPrefs.SetInt("Voodoo.Sauce.Privacy.AnalyticsConsent", consent ? 1 : 0);
		}

		private bool GetAnalyticsConsent()
		{
			return NintendoPlayerPrefs.GetInt("Voodoo.Sauce.Privacy.AnalyticsConsent", -1) == 1;
		}

		private string GetPrivacyVersion()
		{
			return NintendoPlayerPrefs.GetString("Voodoo.Sauce.Privacy.PrivacyVersion", "0");
		}

		private void CachePrivacyVersion(string privacyVersion)
		{
			NintendoPlayerPrefs.SetString("Voodoo.Sauce.Privacy.PrivacyVersion", privacyVersion);
		}

		private bool GetAlreadyAppliedGdpr()
		{
			return NintendoPlayerPrefs.HasKey("Voodoo.Sauce.Privacy.PrivacyVersion");
		}

		private void CacheSixteenOrOlder(bool isSixteenOrOlder)
		{
			NintendoPlayerPrefs.SetInt("Voodoo.Sauce.Privacy.IsOverSixteen", isSixteenOrOlder ? 1 : 0);
		}

		private bool GetSixteenOrOlder()
		{
			return NintendoPlayerPrefs.GetInt("Voodoo.Sauce.Privacy.IsOverSixteen", -1) == 1;
		}

		private void CacheNeedSendConsent(bool needSend)
		{
			NintendoPlayerPrefs.SetInt("Voodoo.Sauce.Privacy.NeedSendConsent", needSend ? 1 : 0);
		}

		private bool NeedSendConsent()
		{
			return NintendoPlayerPrefs.GetInt("Voodoo.Sauce.Privacy.NeedSendConsent", -1) == 1;
		}

		private static void CacheConsentDate()
		{
			NintendoPlayerPrefs.SetInt("Voodoo.Sauce.Privacy.LastConsentDate", TimeUtils.NowAsTimeStamp());
		}

		private static int GetConsentDate()
		{
			return NintendoPlayerPrefs.GetInt("Voodoo.Sauce.Privacy.LastConsentDate", 0);
		}

		private void CacheAdTrackingEnabled(bool adTrackingEnabled)
		{
			NintendoPlayerPrefs.SetInt("Voodoo.Sauce.Privacy.AdTrackingEnabled", adTrackingEnabled ? 1 : 0);
		}

		private bool GetCachedAdTrackingEnabled()
		{
			return NintendoPlayerPrefs.GetInt("Voodoo.Sauce.Privacy.AdTrackingEnabled", 0) == 1;
		}

		private void CachePrivacyList()
		{
			NintendoPlayerPrefs.SetString("Voodoo.Sauce.Privacy.List", string.Join(",", PrivacyUtils.GetPrivacyPolicyUrls().ToArray()));
		}

		private string[] GetPrivacyList()
		{
			return NintendoPlayerPrefs.GetString("Voodoo.Sauce.Privacy.List", "").Split(',');
		}

		private bool IsCachePresent()
		{
			return NintendoPlayerPrefs.HasKey("Voodoo.Sauce.Privacy.IsOverSixteen");
		}

		private void CacheUserRequestedToBeForgotten(bool value)
		{
			NintendoPlayerPrefs.SetInt("Voodoo.Sauce.Privacy.UserRequestedToBeForgotten", value ? 1 : 0);
		}

		public override bool UserRequestedToBeForgotten()
		{
			return NintendoPlayerPrefs.GetInt("Voodoo.Sauce.Privacy.UserRequestedToBeForgotten", -1) == 1;
		}

		private void CacheCurrentPlayDate()
		{
			NintendoPlayerPrefs.SetInt("Voodoo.Sauce.Privacy.LastPlayDate", TimeUtils.NowAsTimeStamp());
		}

		private int GetLastPlayDate()
		{
			return NintendoPlayerPrefs.GetInt("Voodoo.Sauce.Privacy.LastPlayDate", 0);
		}

		private void CacheCurrentPlaytime(int playtimeInSecond)
		{
			NintendoPlayerPrefs.SetInt("Voodoo.Sauce.Privacy.LastPlayTime", playtimeInSecond);
		}

		private int GetLastPlaytimeInSecond()
		{
			return NintendoPlayerPrefs.GetInt("Voodoo.Sauce.Privacy.LastPlayTime", 0);
		}
	}
}
